import axios from './interceptors.js';
import { Message } from 'element-ui';
import store from '@/store';

let source = axios.CancelToken.source();
const maskThrottle = 500; // 蒙版节流时长

export default {
  async request(method, url, options = {}) {
    let isReturn = false;
    if (!options.waitingMask) {
      setTimeout(() => { // 蒙版节流
        if (!isReturn && !store.getters.isShowLayoutMask) {
          store.commit('layout/showLayoutMask', true);
        }
      }, maskThrottle);
    }
    const result = await axios({
      method,
      url,
      cancelToken: source.token,
      timeout: 15000, // 多少毫秒后请求超时
      ...options
    }).then(res => {
      isReturn = true;
      if (!options.waitingMask && store.getters.isShowLayoutMask) {
        store.commit('layout/showLayoutMask', false);
      }
      res.data.type = res.data.code == 200 ? 'success' : 'error';
      if (res.data.code == 401) {
        res.data.msg = res.data.message;
        res.data.message = '';
      }
      return res.data;
    }).catch(err => {
      isReturn = true;
      const response = {
        code: 0,
        message: '',
        data: {},
        type: 'error'
      };
      if (err.response) { // 请求已发出，但服务器使用状态代码进行响应
        response.code = err.response.status;
        response.message = '请求服务器出错！错误状态码：' + err.response.status;
      } else if (err.__CANCEL__) { // 手动取消请求
        response.code = 601;
        response.type = 'warning';
        response.message = err.message;
      } else if (err.code == 'ECONNABORTED') { // 请求超时
        response.code = 602;
        response.message = '请求服务器超时！';
      } else { // 连接服务器失败
        response.code = 600;
        response.message = '无法连接服务器！';
      }
      if (!options.waitingMask && store.getters.isShowLayoutMask) {
        store.commit('layout/showLayoutMask', false);
      }
      return response;
    });
    return result;
  },
  abort(msg) {
    source.cancel(msg);
    source = axios.CancelToken.source();
  },
  async waiting(https) {
    let isReturn = false;
    setTimeout(() => { // 蒙版节流
      if (!isReturn && !store.getters.isShowLayoutMask) {
        store.commit('layout/showLayoutMask', true);
      }
    }, maskThrottle);
    const result = await axios.all(https).then(axios.spread(function() {
      isReturn = true;
      const resTip = {
          code: 200,
          message: '',
          data: {},
          type: 'success'
        },
        res = [];
      let handleCancel = null;
      for (let i = 0; i < arguments.length; i++) {
        res.push(arguments[i]);
        if (res[i].code != 200) {
          resTip.code = 700; // 综合错误
          resTip.type = 'error';
          if (resTip.message) {
            resTip.message += `\n${ res[i].message }`;
          } else {
            resTip.message += res[i].message;
          }
        }
      }
      handleCancel = res.find(item => item.code == 601); // 寻找是否手动取消请求
      if (handleCancel) {
        resTip.code = 601; // 手动取消请求
        resTip.type = 'warning';
        resTip.message = handleCancel.message;
      }
      if (store.getters.isShowLayoutMask) {
        store.commit('layout/showLayoutMask', false);
      }
      return {
        res,
        resTip
      };
    }));
    return result;
  },
  tip(res, options = { duration: 2000 }) {
    if (res && res.message) {
      Message.closeAll();
      Message({
        type: res.type,
        message: res.message,
        ...options
      });
    }
  }
};
